package com.example.mapsapp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity implements View.OnClickListener{
public static Context cont;
EditText userString;
EditText  passwordString;
public static String user;
String password;
public static  Verify set =new Verify();
public  final String QUERY_STRING=   "http://softeng.cs.uwosh.edu/students/cs342g2/derek.php?";
private UserLoginTask mAuthTask = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		String user;
		String password;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		Button log = (Button) findViewById(R.id.buttonLogin);
		log.setOnClickListener(this);
		
		Button log1 = (Button) findViewById(R.id.buttonRegister);
		log1.setOnClickListener(this);
		 userString = (EditText) findViewById(R.id.editTextLogin);
		 passwordString = (EditText) findViewById(R.id.editTextPassword);
		 
	}

	public void onClick(View v){

		switch (v.getId())
		     {
			     case R.id.buttonLogin:
			    	 attemptLogin();
			      	break;
			     case R.id.buttonRegister:
			     	 regClick();
			     	 break;
		      }
	}
	
	
   private void regClick()
   {
	   Intent iv = new Intent(this,Register.class);
	   startActivity(iv);
   } 
   private void attemptLogin()
   {
	   if (mAuthTask != null) {
			return;
		}
	// Reset errors.
			userString.setError(null);
			passwordString.setError(null);

			// Store values at the time of the login attempt.
			
			 user = userString.getText().toString();
			 password = passwordString.getText().toString();

			boolean cancel = false;
			View focusView = null;

			// Check for a valid password.
			if (TextUtils.isEmpty(password)) {
				passwordString.setError("wrong password");
				focusView = passwordString;
				cancel = true;
			} else if (password.length() < 4) {
				passwordString.setError("Password is too short");
				focusView = passwordString;
				cancel = true;
			}

			// Check for a valid email address.
			if (TextUtils.isEmpty(user)) {
				userString.setError("Empty User Name");
				focusView = userString;
				cancel = true;
			} else if (user.length()> 20) {
				 userString.setError("UserName is too long not more than 20 characters");
				focusView = userString;
				cancel = true;
			}

			if (cancel) {
				// There was an error; don't attempt login and focus the first
				// form field with an error.
			 focusView.requestFocus();
			} else {
				// Show a progress spinner, and kick off a background task to
				// perform the user login attempt.
				mAuthTask = new UserLoginTask();
				mAuthTask.execute();
						
			}

   } 
   
   public class UserLoginTask extends AsyncTask<Void, Void, Verify> 
   { 
	 		@Override 
		protected Verify doInBackground(Void... params)
		{
			XmlPullParser batman = tryDown(user,password);
			 try {
				 Log.i("Request failed5", "these is it  in background");
				Login.set = trygeMessage(batman);
				
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				 Log.i("Request failed5", "these is it  in background");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				 Log.i("Request failed5", "these is it  in background");
			}
			
			return set;
			
         }  
		
		private XmlPullParser tryDown(String d,String r)
		   {
			System.out.println("firstparam "+ d+"  Second param "+ r);
			try{
			 StringBuilder b = new StringBuilder(QUERY_STRING);
		       b.append("user=");
		       b.append(d);
	              b.append("&password=");
	              b.append(r);
		       URI url  = new URI(b.toString());
		       DefaultHttpClient client = new DefaultHttpClient();

		       HttpGet method = new HttpGet(url);

		       HttpResponse res = client.execute(method);

		      
			  XmlPullParser superman = XmlPullParserFactory.newInstance().newPullParser();
			  superman.setInput(new InputStreamReader(res.getEntity().getContent()));
			  Log.i("Request failed3", "ok in first method");
			 

			  return superman;
			}
			catch(XmlPullParserException e)
			{
				 
				Log.i("Request failed1", e.toString());
			}
			catch(IOException e)
			{
				
				Log.i("Request failed2", e.toString());
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				Log.i("Request failed3", e.toString());
				//e.printStackTrace();
				
			}
			
			return null;
		    }
		private Verify trygeMessage(XmlPullParser batman) throws XmlPullParserException, IOException {
			     Verify results = new Verify();
					      
			    int eventType;			 
				eventType = batman.getEventType();
				String currentTag = null;
		        String title = null;
		        boolean done = false;
		        String TagTest = null;
		        int i  = 0;
		        while (eventType != XmlPullParser.END_DOCUMENT) {
		        	    
		        	     
		            if(eventType == XmlPullParser.START_DOCUMENT) {
		                 
		                System.out.println("Start document");
		            } else if(eventType == XmlPullParser.END_DOCUMENT) {
		            	
		                System.out.println("End document");
		            } else if(eventType == XmlPullParser.START_TAG) {
		            	TagTest = batman.getName();
		                System.out.println("Start tag "+batman.getName());
		            } else if(eventType == XmlPullParser.END_TAG) {
		            	   TagTest =" ";
		            	   
		            	  }
		               
		             else if(eventType == XmlPullParser.TEXT) {
		            	if (TagTest.equals("User"))
		            	  {
		            		results.setValue(batman.getText());
		            		 System.out.println(results);
		            	  }
		            	
		           	  
		                 
		            }
		             i++;
		            eventType = batman.next();
		           }     
		       
		        
		          
		        return results;
		}
		@Override
		protected void onPostExecute(Verify success) {
			mAuthTask = null;
			System.out.println("sucess "+ success.getValue());
		    if (success.getValue().equals("Pass")) {
		   	Intent iv = new Intent(Login.this,MainActivity.class);
			 startActivity(iv);
			}
		    else {
			    userString.setError("Invalid Credential");
				userString.requestFocus();
			}
		}
      }

	
}
